<template>
  <view class="blog">
    <view class="wrap">
      <u-swiper :list="bannerList" :title="true"></u-swiper>
    </view>
    <view id="wind-height">
      <view class="search">
        <u-search
          class="input"
          border-color="#e3742e"
          bg-color="#fff"
          :show-action="false"
          placeholder="请输入标题进行搜索"
          v-model="keyword"
          @search="getData"
        ></u-search>
        <u-icon @click="addBlog" name="plus-circle" color="#e3742e" size="56"></u-icon>
      </view>
      <view>
        <u-tabs-swiper
          active-color="#e3742e"
          ref="uTabs"
          :list="listd"
          :current="gcurrent"
          @change="tabsChange"
          :is-scroll="false"
          swiperWidth="750"
        ></u-tabs-swiper>
      </view>
    </view>
    <swiper :style="`height: ${contentHeight}px`" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
      <swiper-item class="swiper-item" v-for="(itm, i) in 2" :key="i">
        <scroll-view
          :refresher-enabled="true"
          @refresherrefresh="refresherrefresh"
          @refresherrestore="refresherrestore"
          :refresher-triggered="triggered"
          scroll-y
          :style="`height: ${contentHeight}px;width: 100%`"
          @scrolltolower="onreachBottom"
        >
          <view class="list" v-if="swiperCurrent === 0">
            <view class="item" v-for="(item, index) in list" :key="index">
              <view @click="detailBlog(item.id)">
                <p class="title">{{ item.title }}</p>
                <view class="content">
                  <view class="main">
                    <view class="user-info">
                      <!-- <u-avatar size="50" :src="item.user.avatar"></u-avatar> -->
                      <image :src="item.user.avatar" mode="scaleToFill" />
                      <p class="name">{{ item.user.username }}</p>
                    </view>
                    <p class="text u-line-2">{{ item.content }}</p>
                  </view>
                  <u-image
                    v-if="item.cover || item.images.split(',')[0]"
                    :src="item.cover || item.images.split(',')[0]"
                    height="120rpx"
                    width="200rpx"
                    border-radius="6rpx"
                  ></u-image>
                </view>
              </view>
            </view>
            <u-loadmore :status="blogSearch.loadStatus" />
          </view>
          <view class="list" v-else>
            <view class="item" v-for="(item, index) in logList" :key="index">
              <view class="phone" @click="detailBlog(item.id)">
                <u-avatar :src="item.user.avatar"></u-avatar>
                <view class="right">
                  <p class="name">{{ item.user.username }}</p>
                  <p class="text">{{ item.content }}</p>
                  <view>
                    <image
                      v-if="item.images.split(',')[0]"
                      v-for="(image, i) in item.images.split(',')"
                      :key="i"
                      :src="image"
                      @click.stop="previewImage(image, item.images.split(','))"
                      mode="aspectFill"
                    />
                  </view>
                </view>
              </view>
              <view class="bottom">
                <view class="time"> {{ item.updateDate }} </view>
                <view class="t_right">
                  <view>{{ item.thumbUpsCount }} <u-icon name="thumb-up" size="32"></u-icon></view>
                  <view style="margin-left: 16rpx">{{ item.commentsCount }} <u-icon name="chat" size="32"></u-icon></view
                ></view>
              </view>
            </view>
            <u-loadmore :status="logSearch.loadStatus" />
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup lang="ts">
  import { apiBlogByPage, apiBlogOne } from '@/api/blog'
  import { uToast } from '@/component/uTools'
  import type { TArtical } from '@/types/blog'
  import { getCurrentInstance, onMounted, ref } from 'vue'

  const sysHeight = uni.getWindowInfo().windowHeight // 可视高度
  const contentHeight = ref(0)
  const listd = [
    {
      name: '博文',
    },
    {
      name: '日志',
    },
  ]
  // 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
  const gcurrent = ref(1) // tabs组件的current值，表示当前活动的tab选项
  const swiperCurrent = ref(1) // swiper组件的current值，表示当前那个swiper-item是活动的
  const uTabs = ref<any>()
  // const loadStatus = ref('loadmore');
  const triggered = ref(false)
  const keyword = ref('')
  const logSearch = ref({
    type: 1,
    key: '',
    page: 1,
    pageSize: 10,
    loadStatus: 'loading',
  })
  const blogSearch = ref({
    type: 2,
    key: '',
    page: 1,
    pageSize: 10,
    loadStatus: 'loading',
  })
  const list = ref<TArtical[]>([])
  const logList = ref<TArtical[]>([])
  const bannerList = [
    {
      image: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
      title: '昨夜星辰昨夜风，画楼西畔桂堂东',
    },
    {
      image: 'https://cdn.uviewui.com/uview/swiper/2.jpg',
      title: '身无彩凤双飞翼，心有灵犀一点通',
    },
    {
      image: 'https://cdn.uviewui.com/uview/swiper/3.jpg',
      title: '谁念西风独自凉，萧萧黄叶闭疏窗，沉思往事立残阳',
    },
  ]

  onMounted(() => {
    const _this = getCurrentInstance()
    const query = uni.createSelectorQuery().in(_this)
    query
      .select('#wind-height')
      .boundingClientRect((data: any) => {
        console.log('节点的距离为' + data.height)
        contentHeight.value = sysHeight - data.height
      })
      .exec()
  })
  // 查看图片
  const previewImage = (image: string, urls: any) => {
    uni.previewImage({
      current: image, // 当前显示图片的http链接
      urls, // 需要预览的图片http链接列表
    })
  }

  // tabs通知swiper切换
  const tabsChange = (index: number) => {
    swiperCurrent.value = index
  }
  // swiper-item左右移动，通知tabs的滑块跟随移动
  const transition = (e: any) => {
    let dx = e.detail.dx
    uTabs.value?.setDx(dx)
  }
  // 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
  // swiper滑动结束，分别设置tabs和swiper的状态
  const animationfinish = (e: any) => {
    let current = e.detail.current
    uTabs.value?.setFinishCurrent(current)
    swiperCurrent.value = current
    gcurrent.value = current
    if ((swiperCurrent.value === 1 && !logList.value.length) || (swiperCurrent.value === 0 && !list.value.length)) {
      getData()
    }
  }

  // scroll-view到底部加载更多
  const onreachBottom = () => {
    console.log('到达底部')
    if (swiperCurrent.value === 1) {
      if (logSearch.value.loadStatus == 'nomore') {
        return
      }
      logSearch.value.loadStatus = 'loading'
      logSearch.value.page = ++logSearch.value.page
      // logList.value += 10;
    } else {
      if (blogSearch.value.loadStatus == 'nomore') {
        return
      }
      blogSearch.value.loadStatus = 'loading'
      blogSearch.value.page = ++blogSearch.value.page
    }
    getData()
  }

  // 下拉刷新
  const refresherrefresh = () => {
    console.log('shuaxin')
    triggered.value = true
    if (swiperCurrent.value === 1) {
      // logSearch.value.loadStatus = 'loading';
      logSearch.value.page = 1
      // logList.value += 10;
    } else {
      // blogSearch.value.loadStatus = 'loading';
      blogSearch.value.page = 1
    }
    getData()
  }

  // 下拉刷新被复位
  const refresherrestore = () => {
    console.log('复位成功')
    uToast('刷新成功')
  }

  // 获取列表数据
  const getData = () => {
    let search = {}
    if (swiperCurrent.value === 1) {
      logSearch.value.key = keyword.value
      search = logSearch.value
    } else {
      blogSearch.value.key = keyword.value
      search = blogSearch.value
    }
    apiBlogByPage(search).then((res: any) => {
      if (res.code === 200) {
        const data = res.data
        if (swiperCurrent.value === 1) {
          const obj = logSearch.value
          logList.value = obj.page === 1 ? data.data : logList.value.concat(data.data)

          if (obj.page * obj.pageSize >= data.total) obj.loadStatus = 'nomore'
        } else {
          const obj = blogSearch.value
          list.value = blogSearch.value.page === 1 ? data.data : list.value.concat(data.data)

          if (obj.page * obj.pageSize >= data.total) obj.loadStatus = 'nomore'
        }
        triggered.value = false
      }
    })
  }
  getData()

  // 搜索列表数据
  // const getDataByKeyword = () => {
  //     apiBlogOne(keyword.value).then((res: any) => {
  //         console.log(res);
  //     })
  // }
  // getDataByKeyword();

  // 新增博客跳转
  const addBlog = () => {
    uni.navigateTo({
      url: '/pages/blog/add/index',
    })
  }

  // 跳转博客详情
  const detailBlog = (id: number) => {
    uni.navigateTo({
      url: '/pages/blog/detail/index?articalId=' + id,
    })
  }
  // const current = ref(0)
  // const change = (index: number) => {
  //     current.value = index;
  // }
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>
